import React, { Component } from 'react';
import { connect } from 'dva';
import { message } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { DATA_ENTRY, AdvancedSearch, NoQueryC, ContentPackage } from '../../../../components';
import TableRender from './tableRender';
import Info from './info';
import DimenStatic from './dimensStatic';
import AssetStatic from './assetStatic';
import { isZiGuanEvir } from '../../../../utils/commonFunc';

@connect(({ profitAndLossM, couponPoolQueryM }) => ({
  profitAndLossM,
  couponPoolQueryM,
}))
export default class PoolAndLossAnaiysis extends Component {
  state = {
    searchData: {
      portfolioCodeList: '',
      portfolioCode: '',
    },
    propsData: {
      portfolioCodeList: '',
      portfolioCode: '',
      time: '',
      begin1: '',
      begin2: '',
    },
    portfolioName: '', // 名称 （用来设置info组件里的标题）
    searchForm: null, // 表单实例
    num: 1,
  };

  componentDidMount() {
    this.getStorageData();
  }

  // 产品组改变
  handPortfolioCodeListChange = (e) => {
    if (e) {
      // this.searchForm.formRef.current.resetFields(['portfolioCode']); // 重置组合和产品
      // this.state.RANGEDATE.reset();
      this.state.PRODUCTGROUPTREE.setSelect();
      console.log('fgfg', this.state.PRODUCTGROUPTREE.state.comp);
      if (e?.info?.children.length > 0) {
        this.setState({
          searchData: {
            portfolioCodeList: e?.key,
            portfolioCode: '',
            portfolioName: e?.info?.title,
          },
        });
      } else {
        message.warning('该组合下无产品');
        this.setState({
          searchData: {
            portfolioCodeList: '',
            portfolioCode: '',
          },
        });
      }
    } else {
      this.state.RANGEDATE.reset();
      this.setState({
        searchData: {
          portfolioCodeList: '',
          portfolioCode: '',
        },
      });
    }
  };

  // 组合和产品改变
  handPortfolioCodeChange = (e) => {
    if (e) {
      this.searchForm.formRef.current.resetFields(['portfolioCodeList']);
      const { info } = e;
      this.setState({
        searchData: {
          ...this.state.searchData,
          portfolioCode: info.portfolioCode,
          portfolioCodeList: '',
          portfolioName: info.portfolioName,
        },
      });
    } else {
      this.setState(
        {
          searchData: {
            portfolioCodeList: '',
            portfolioCode: '',
            portfolioName: '',
          },
        },
        () => {
          this.state.RANGEDATE.reset();
        },
      );
    }
  };

  // 点击查询
  setPorpsData = (e) => {
    const { searchData } = this.state;
    if (!searchData.portfolioCode && !searchData.portfolioCodeList) {
      message.warning('请选择产品组或产品');
      return;
    }

    if (!e.begin1 || !e.begin2) {
      message.warning('请选择时间区间');
      return;
    }
    if (e.time == '3' || e.time == '4' || e.time == '5' || e.time == '6') message.warning('数据加载时间可能较长请耐心等待!');
    this.setState({
      propsData: {
        ...this.state.searchData,
        time: e.time || '0',
        begin1: e.begin1 && e.begin1.format('YYYY-MM-DD'),
        begin2: e.begin2 && e.begin2.format('YYYY-MM-DD'),
      },
      num: `use${(((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)}`,
    });
  };

  // 从组合概览跳转   拿到sessionStorage中的查询条件
  getStorageData = () => {
    const overviewData = JSON.parse(sessionStorage.getItem('searchObj'));
    const changeDMY = sessionStorage.getItem('changeDMY');
    if (overviewData) {
      const { portfolioCode, timeRange, beginDate, endDate, portfolioName } = overviewData;

      this.setState({
        searchData: {
          portfolioCode,
          timeRange,
          beginDate,
          endDate,
          portfolioName,
        },
        changeDMY,
      });
    }
  };

  // 获取子组件接口返回的数据用于匹配code
  changePortfolioCodeInitValue = (data) => {
    const overviewData = JSON.parse(sessionStorage.getItem('searchObj'));
    sessionStorage.removeItem('searchObj');
    const { portfolioCode } = overviewData || {};
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.portfolioCode === portfolioCode) {
        this.setState(
          {
            codeKey: item.key,
          },
          () => {
            // 更新数据完成之后触发查询
            const { codeKey } = this.state;
            const { beginDate, endDate, timeRange } = this.state.searchData;
            const changeSearchData = {
              begin1: moment(beginDate),
              begin2: moment(endDate),
              beginDate: moment(beginDate),
              endDate: moment(endDate),
              timeRange,
              portfolioCode: codeKey,
            };
            this.setPorpsData(changeSearchData);
          },
        );
      }
    }
  };

  render() {
    const { propsData, searchData = {}, codeKey, changeDMY } = this.state;
    const { timeRange, beginDate, endDate } = searchData;
    const { portfolioName, ...paramsData } = propsData;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioCodeList',
          title: '产品组',
          type: DATA_ENTRY.PRODUCTGROUP,
          multiple: false,
          disabled: isZiGuanEvir(),
          onRef: (ref) => this.setState({ PRODUCTGROUP: ref }),
          onChange: this.handPortfolioCodeListChange,
        },
        {
          dataIndex: 'portfolioCode',
          title: '产品',
          type: isZiGuanEvir() ? DATA_ENTRY.PRODUCTLIST : DATA_ENTRY.PRODUCTGROUPTREE,
          multiple: false,
          onRef: (ref) => this.setState({ PRODUCTGROUPTREE: ref }),
          onChange: this.handPortfolioCodeChange,
          ...(isZiGuanEvir() ? { dataType: 2 } : null),
          changePortfolioCodeInitValue: this.changePortfolioCodeInitValue,
          initialValue: codeKey,
        },
        searchData.portfolioCode
          ? {
              selectIndex: 'time',
              startIndex: 'begin1',
              endIndex: 'begin2',
              type: DATA_ENTRY.HOlDDATERANGEC,
              productCode: searchData.portfolioCode,
              flag: '2',
              defaultType: timeRange || '2',
              initialValue: beginDate && { beginDate: moment(beginDate), endDate: moment(endDate) },
            }
          : {
              type: DATA_ENTRY.RANGEDATE,
              dataIndex: ['begin1', 'begin2'],
              title: '时间区间',
              disabled: !searchData.portfolioCode && !searchData.portfolioCodeList,
              onRef: (ref) => this.setState({ RANGEDATE: ref }),
            },
      ],
      onQuery: (e) => {
        this.setPorpsData(e);
      },
      onClear: () => {
        this.setState({
          searchData: {
            portfolioCodeList: '',
            portfolioCode: '',
          },
          codeKey: '',
          timeRange: '',
          changeDMY: '',
        });
      },
    };
    return (
      <ContentPackage
        title='盈亏分析'
        contentHtml={
          <div style={{ height: '100%', padding: ' 0 12px' }}>
            <div style={{ marginBottom: 10 }}>
              <AdvancedSearch {...searchProps} onRef={(ref) => (this.searchForm = ref)} />
            </div>

            {propsData.portfolioCode === '' && propsData.portfolioCodeList === '' ? (
              <NoQueryC />
            ) : (
              <div>
                <div>
                  <Info
                    portfolioName={portfolioName}
                    num={this.state.num}
                    portfolioCode={paramsData.portfolioCode}
                    portfolioCodeList={Number(paramsData.portfolioCodeList)}
                    index={paramsData.time}
                    beginDate={paramsData.begin1}
                    endDate={paramsData.begin2}
                  />
                </div>

                <div>
                  <DimenStatic
                    num={this.state.num}
                    portfolioCode={paramsData.portfolioCode}
                    portfolioCodeList={Number(paramsData.portfolioCodeList)}
                    index={paramsData.time}
                    beginDate={paramsData.begin1}
                    endDate={paramsData.begin2}
                    changeDMY={changeDMY}
                  />
                </div>

                <div>
                  <AssetStatic
                    num={this.state.num}
                    portfolioCode={paramsData.portfolioCode}
                    portfolioCodeList={Number(paramsData.portfolioCodeList)}
                    index={paramsData.time}
                    beginDate={paramsData.begin1}
                    endDate={paramsData.begin2}
                  />
                </div>

                <div>
                  <TableRender
                    num={this.state.num}
                    portfolioCode={paramsData.portfolioCode}
                    portfolioName={portfolioName}
                    portfolioCodeList={Number(paramsData.portfolioCodeList)}
                    index={paramsData.time}
                    beginDate={paramsData.begin1}
                    endDate={paramsData.begin2}
                  />
                </div>
              </div>
            )}
          </div>
        }
      />
    );
  }
}
